import express from 'express'
import bodyParser from 'body-parser'
import os from 'os'
// 接收摄像头信息服务
class RevService {
  // 消息回调函数
  msgcallback = null
  // 当前启动的服务
  currentService = null
  // 当前创建epress实例
  app = null
  // 服务默认端口号
  port = 37821
  constructor() {}
  // 获取本地ip地址
  getLocalIp() {
    const interfaces = os.networkInterfaces()
    for (const devName in interfaces) {
      const iface = interfaces[devName]

      for (let i = 0; i < iface.length; i++) {
        const alias = iface[i]
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal &&
          alias.address.includes('192.168')
        ) {
          // 返回找到的第一个符合条件的内网IP地址
          return alias.address
        }
      }
    }
    return '0.0.0.0'
  }
  // 开启后端服务
  start(ip) {
    /**
     * @type {express}
     */
    this.app = express()
    this.app.use(bodyParser.json({ limit: '50mb' }))
    this.app.all('*', (req, res) => {
      console.log('exiting someone visited')
      const body = req.body
      // 回传主进程消息
      this.msgcallback && this.msgcallback(body)
      // 设置相应体
      let responseContent = {
        id: body.id,
        sesssionId: body.sessionId,
        code: '0',
        message: '执行成功',
        memo: null,
        data: {
          systemTime: Date.now()
        }
      }
      // 设置响应头，指定返回内容为 JSON 格式
      res.setHeader('Content-Type', 'application/json')
      // 设置状态码
      res.status(200)
      // 返回json数据
      res.json(responseContent)
    })
    return new Promise((res, rej) => {
      try {
        if (ip) {
          let hostName = ip.split(':')[0]
          this.currentService = this.app.listen(this.port, hostName, () => {
            res(true)
          })
        } else {
          this.currentService = this.app.listen(this.port, () => {
            let ip = this.getLocalIp()
            console.log('receiver server has started at:', `${ip}:${this.port}`)
            res(true)
          })
        }
      } catch {
        this.port++
        this.currentService = this.app.listen(this.port, () => {
          console.log('receiver server has started at:', `http://localhost:${this.port}`)
        })
        rej(false)
      }
    })
  }
  // 停止服务
  stop() {
    if (!this.currentService) return Promise.resolve(true)
    return new Promise((res, rej) => {
      // 关闭当前服务
      this.currentService.close(() => {
        this.app = null
        this.currentService = null
        console.log('server has closed')
        res(true)
      })
    })
  }
  // 设置消息回调函数
  setMsgCallback(callback) {
    this.msgcallback = callback
  }
}
const service = new RevService()
export default service
